package com.facebook.app.client.view;

import java.util.ArrayList;
import java.util.List;

import com.facebook.app.client.ClusteringMethod;
import com.facebook.app.client.ClusteringMethod.ClusteringType;
import com.facebook.app.client.presenter.ClusteringEndedPresenter;
import com.facebook.app.client.uiElements.ClusterableCell;
import com.facebook.app.client.uiElements.ClusterableCompositeCell;
import com.facebook.app.client.uiElements.FacebookDataCell;
import com.facebook.app.shared.clustering.Clusterable;
import com.facebook.app.shared.facebookData.FacebookData;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.HasCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TreeNode;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.SingleSelectionModel;

public class ClusteringEndedView extends Composite implements ClusteringEndedPresenter.Display {
	
	private final ClusteringType selectedClusteringType;
	
	private final TabPanel tabPanel = new TabPanel(); // 1.5 em?  new TabLayoutPanel(3, Unit.EM);
	
	private CellTree clusteringResultsTree;
	
	private final VerticalPanel selectedFriendsPanel = new VerticalPanel();
	private final Label selectedFriendsLabel = new Label("No friends selected");
	private CellList<FacebookData> selectedFriends;
	
	private final VerticalPanel commonLikesPanel = new VerticalPanel();
	private final Image loadingImage = new Image("http://www.crewcheck.org/images/loading.gif"); // TODO as ImageResource (and not as url)
	private final Label commonLikesLabel = new Label("No common likes");
	private CellList<FacebookData> commonLikes;
	
	public ClusteringEndedView(ClusteringType selectedClusteringType) {
		this.selectedClusteringType = selectedClusteringType;
		
		initWidget(tabPanel);
	}
	
	@Override
	public Panel getSelectedFriendsPanel() {
		return selectedFriendsPanel;
	}
	
	@Override
	public Label getSelectedFriendsLabel() {
		return selectedFriendsLabel;
	}
	
	@Override
	public CellList<FacebookData> getSelectedFriends() {
		return selectedFriends;
	}
	
	@Override
	public Panel getCommonLikesPanel() {
		return commonLikesPanel;
	}
	
	@Override
	public Image getLoadingImage() {
		return loadingImage;
	}
	
	@Override
	public Label getCommonLikesLabel() {
		return commonLikesLabel;
	}
	
	@Override
	public CellList<FacebookData> getCommonLikes() {
		return commonLikes;
	}
	
	@Override
	public TabPanel getTabPanel() {
		return tabPanel;
	}
	
	@Override
	public Widget asWidget(List<Clusterable> clusteringResults, SelectionModel<Clusterable> selectionModelForClusterables, SelectionModel<ClusteringMethod> clusteringMethodSelectionModel) {

		FacebookDataCell dataCell = new FacebookDataCell();
		
		selectedFriends = new CellList<FacebookData>(dataCell);
		selectedFriends.setSelectionModel(createSingleSelectionModel());
		selectedFriends.setPageSize(30);
		
		selectedFriendsLabel.setVisible(false);
		selectedFriendsPanel.add(selectedFriendsLabel);
		selectedFriendsPanel.setCellHorizontalAlignment(selectedFriendsLabel, HasHorizontalAlignment.ALIGN_CENTER);
		selectedFriendsPanel.add(selectedFriends);
		
		commonLikes = new CellList<FacebookData>(dataCell);
		commonLikes.setSelectionModel(createSingleSelectionModel());
		commonLikes.setPageSize(30);
		
		loadingImage.setVisible(false);
		commonLikesPanel.add(loadingImage);
		commonLikesPanel.setCellHorizontalAlignment(loadingImage, HasHorizontalAlignment.ALIGN_CENTER);
		
		commonLikesLabel.setVisible(false);
		commonLikesPanel.add(commonLikesLabel);
		commonLikesPanel.setCellHorizontalAlignment(commonLikesLabel, HasHorizontalAlignment.ALIGN_CENTER);
		commonLikesPanel.add(commonLikes);
	
		CellTree.Resources resources = GWT
		.create(CellTree.BasicResources.class);
		
		clusteringResultsTree = new CellTree(selectedClusteringType.display(clusteringResults, selectionModelForClusterables,
				new ClusterableCompositeCell(createHasCellList(selectionModelForClusterables))), null, resources);
		clusteringResultsTree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
		clusteringResultsTree.setAnimationEnabled(true);
//		clusteringResultsTree.setStylePrimaryName("gwt-CellTree");
		
		openTreeNodes(clusteringResultsTree.getRootTreeNode());
		
		tabPanel.add(clusteringResultsTree, "Cluster tree");
		tabPanel.add(selectedFriendsPanel, "Selected friends");
		tabPanel.add(commonLikesPanel, "Common likes");
		
		VerticalPanel clusterChoicePanel = new VerticalPanel();
		Widget clusterChoiceWidget = new ClusterStrategyChoiceView().asWidget(clusteringMethodSelectionModel);
		clusterChoicePanel.add(clusterChoiceWidget);
		clusterChoicePanel.setCellHorizontalAlignment(clusterChoiceWidget, HasHorizontalAlignment.ALIGN_CENTER);
		
		tabPanel.add(clusterChoicePanel, "Choose another strategy");
		tabPanel.setAnimationEnabled(true);
		
		tabPanel.selectTab(tabPanel.getWidgetIndex(clusteringResultsTree));
		
//		 for (int i = 0; i < tabLayout.getWidgetCount(); i++) {
//		        final Widget widget = tabLayout.getWidget(i);
//		        DOM.setStyleAttribute(widget.getElement(), "position", "relative");
//
//		        final Element parent = DOM.getParent(widget.getElement());
//		        DOM.setStyleAttribute(parent, "overflowX", "visible");
//		        DOM.setStyleAttribute(parent, "overflowY", "visible");
//		 }
		
		return this;
	}	
	
	private void openTreeNodes(TreeNode rootNode) {
		
		for (int i = 0; i < rootNode.getChildCount(); i++) {
			TreeNode node = rootNode.setChildOpen(i, true);
			
			if (node != null) {
				openTreeNodes(node);
			}
		}
	}
	
	private SingleSelectionModel<FacebookData> createSingleSelectionModel() {
		
		final SingleSelectionModel<FacebookData> selectionModel = new SingleSelectionModel<FacebookData>();
		
		selectionModel
		.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
			@Override
			public void onSelectionChange(SelectionChangeEvent event) {
				FacebookData selected = selectionModel
						.getSelectedObject();

				if (selected != null) {

					final DialogBox dialogBox = createDialogBox(selected);
					dialogBox.center();
				}
			}
		});
		
		return selectionModel;
	}
	
	private DialogBox createDialogBox(FacebookData facebookData) {
		
		final StringBuilder profileLinkHtml = new StringBuilder("http://www.facebook.com/profile.php?id=");
		profileLinkHtml.append(facebookData.getId());
		
		final StringBuilder largeProfilePicHtml = new StringBuilder("http://graph.facebook.com/");
		largeProfilePicHtml.append(facebookData.getId());
		largeProfilePicHtml.append("/picture?type=large");
		
		final DialogBox dialogBox = new DialogBox();
		dialogBox.ensureDebugId("facebookDataDialogBox");
		dialogBox.setGlassEnabled(true);
		dialogBox.setAnimationEnabled(true);
		dialogBox.setAutoHideEnabled(true);
		
		dialogBox.setText(facebookData.getName());
		
		VerticalPanel dialogContents = new VerticalPanel();
		dialogContents.setSpacing(4);
		
		dialogBox.setWidget(dialogContents);
		
		Button profileLinkButton = new Button("Profile", new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				Window.open(profileLinkHtml.toString(), "_blank", "");
			}
		});
		dialogContents.add(profileLinkButton);
		dialogContents.setCellHorizontalAlignment(profileLinkButton, HasHorizontalAlignment.ALIGN_CENTER);
		
		Image largeProfilePic = new Image(largeProfilePicHtml.toString());
		dialogContents.add(largeProfilePic);
		dialogContents.setCellHorizontalAlignment(largeProfilePic, HasHorizontalAlignment.ALIGN_CENTER);
		
		return dialogBox;
	}
	
	private List<HasCell<Clusterable, ?>> createHasCellList(final SelectionModel<Clusterable> selectionModel) {
		
		List<HasCell<Clusterable, ?>> hasCells = new ArrayList<HasCell<Clusterable, ?>>();
		hasCells.add(new HasCell<Clusterable, Boolean>() {
			
			private final CheckboxCell cell = new CheckboxCell(true, false);
			
			public Cell<Boolean> getCell() {
				return cell;
			}
			
			public FieldUpdater<Clusterable, Boolean> getFieldUpdater() {
				return null;
			}
			
			public Boolean getValue(Clusterable object) {
				return selectionModel.isSelected(object);
			}
		});
		
		hasCells.add(new HasCell<Clusterable, Clusterable>() {
			
			private final ClusterableCell cell = new ClusterableCell();
			
			public Cell<Clusterable> getCell() {
				return cell;
			}
			
			public FieldUpdater<Clusterable, Clusterable> getFieldUpdater() {
				return null;
			}
			
			public Clusterable getValue(Clusterable object) {
				return object;
			}
		});	
		return hasCells;
	}
	
}
